<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="showAddCateDialog">
            添加商品
          </el-button>
        </el-col>
      </el-row>

      <!-- tree-table -->
      <tree-table
        :data="cateList"
        :columns="columns"
        show-index
        :expand-type="false"
        index-text="#"
        border
        :show-row-hover="false"
        :selection-type="false"
        class="tree"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCate(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>

      <!-- 添加分类 -->
      <el-dialog
        :visible.sync="addDialogVisible"
        title="添加分类"
        width="30%"
        @close="closeAdd"
      >
        <!-- 内容主体区 -->
        <el-form
          ref="addFormRef"
          label-width="90px"
          :model="addCateForm"
          :rules="addCateFormRules"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectCateKeys"
              :options="parentcateList"
              :props="cateProps"
              clearable
              change-on-select
              @change="cateChange"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeAdd">取消</el-button>
            <el-button type="primary" @click="addCate">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!--  编辑分类名称 -->
      <el-dialog
        :visible.sync="editDialogVisible"
        title="修改分类"
        width="30%"
        @close="closeEdit"
      >
        <!-- 内容主体区 -->
        <el-form
          ref="editFormRef"
          label-width="90px"
          :model="editCateForm"
          :rules="editCateFormRules"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeEdit">取消</el-button>
            <el-button type="primary" @click="EditCate">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import ZkTable from "vue-table-with-tree-grid";
import { MessageBox, Message } from "element-ui";
export default {
  name: "Cate",
  components: {
    "tree-table": ZkTable,
  },
  data() {
    return {
      editDialogVisible: false,
      selectCateKeys: [],
      parentcateList: [],
      // 级联选择框的配置对象
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      addCateForm: {
        cat_name: "",
        // 父级分类id
        cat_pid: 0,
        // 分类层级 默认为一级分类
        cat_level: 0,
      },
      editCateForm: {
        cat_name: "",
        cat_id: 0,
      },
      addCateFormRules: {
        cat_name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
        ],
      },
      // 编辑分类
      editCateFormRules: {
        cat_name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
        ],
      },
      // 添加分类
      addDialogVisible: false,
      // 获取商品列表的数据的参数
      queryInfo: {
        type: 3,
        // 当前页码值
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 5,
      },
      total: 0,
      cateList: [],
      // treetable的表格各列的配置
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
          width: "200",
        },
      ],
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取商品列表
    async getCateList() {
      const { data: res } = await this.$http.get("/categories", {
        params: this.queryInfo,
      });
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取商品列表失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    // 监听页码内容大小改变
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getCateList();
    },
    // 监听页面改变
    handleCurrentChange(newnum) {
      this.queryInfo.pagenum = newnum;
      this.getCateList();
    },
    // 获取分类选择器数据
    async getParentCateList() {
      const { data: res } = await this.$http.get("/categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      this.parentcateList = res.data;
    },
    showAddCateDialog() {
      // 先获取分类选择器数据,在弹出框
      this.getParentCateList();
      this.addDialogVisible = true;
    },
    // 点击确定添加
    addCate() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "/categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) return this.$message.error("添加分类失败");
        this.$message.success("添加分类成功");
        this.getCateList();
        this.addDialogVisible = false;
      });
    },
    // 改变级联选择
    cateChange() {
      if (this.selectCateKeys.length > 0) {
        this.addCateForm.cat_pid =
          this.selectCateKeys[this.selectCateKeys.length - 1];
        // 为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectCateKeys.length;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
      // console.log(this.selectCateKeys);
    },
    //  关闭添加弹出框,清空列表
    closeAdd() {
      this.addDialogVisible = false;
      this.$refs.addFormRef.resetFields();
      this.selectCateKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    // 点击编辑
    editCate(row) {
      console.log(row);
      this.editCateForm.cat_name = row.cat_name;
      this.editCateForm.cat_id = row.cat_id;
      this.editDialogVisible = true;
    },
    closeEdit() {
      this.editDialogVisible = false;
      this.$refs.editFormRef.resetFields();
    },
    EditCate() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `/categories/${this.editCateForm.cat_id}`,
          {
            cat_name: this.editCateForm.cat_name,
          }
        );
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("修改分类失败");
        this.$message.success("修改分类成功");
        this.getCateList();
        this.editDialogVisible = false;
      });
    },
    // 点击删除
    async deleteCate(id) {
      const res = await MessageBox.confirm(
        "此操作将永久删除该分类,是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        Message({
          type: "info",
          message: "已取消删除",
        });
      });
      // 如果用户确认了删除,返回字符串confirm
      if (res === "confirm") {
        const { data: res } = await this.$http.delete("/categories/" + id);
        console.log(res);
        if (res.meta.status !== 200) return this.$message.error("删除分类失败");
        Message({
          type: "success",
          message: "删除分类成功",
        });
        this.getCateList();
      }
    },
  },
};
</script>

<style lang='less' scoped>
.tree {
  margin: 15px 0;
}
</style>